package cn.wolfcode.rbac.springsecurity.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.springsecurity.detail.EmployeeDetails;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

import static cn.wolfcode.rbac.common.RedisKeyPrefix.EMPLOYEE_EXPRESSION_PREFIX;

/**
 * 自定义UserDetailsService数据源
 */
@Service
public class EmployeeDetailsService implements UserDetailsService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //1.根据username获取用户信息
        Employee employee = employeeMapper.selectByName(username);
        //如果有该用户信息，则把用户封装到UserDetails中,没有则抛出异常
        if(employee == null){
            throw new UsernameNotFoundException("用户名错误");
        }

//        //2.如果不是超级管理员，根据员工id查询权限。如果是则为null
        Set<String> expressions = null;
        if (!employee.getAdmin()) {
            //根据员工id查询所有的权限
            expressions = permissionMapper.queryExpressionByEmployeeId(employee.getId());
        }

        //3.把用户信息和权限封装到UserDetails中并返回，解决方案：自定义UserDetails
        EmployeeDetails employeeDetails = new EmployeeDetails(employee,expressions);
        return employeeDetails;
    }
}
